package org.optaplanner.examples.apsplanning.dao;

import org.optaplanner.examples.apsplanning.domain.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author andaolong
 * @time 2021年3月27日11:23:11
 * 从数据库中获取数据
 */
@Component
public class DeviceDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    Long taskPlanningId = 1L;

    //查询所有的device的id，返回device类型的list，里面还未填入machiningType
    public List<Device> getDeviceListFromDB() {

        //首先查询到所有的device_id
        String sql = "select distinct device_id,device_run_cost_per_hour from device natural left join device_info";
        //将查询到的所有device_id存到一串<Device>的list里面
        //return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Device.class));

        //调试用
        //List<Device> deviceList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Device.class));
        //for(Device device:deviceList){
        //    System.out.println("deviceDao获取到的deviceId为："+device.getDeviceId());
        //}
        //return deviceList;

        //给从数据库中获得的device添加上id，排程的时候需要依靠这个id进行移动操作
        List<Device> deviceList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Device.class));
        List<Device> deviceListWithSuperId = new ArrayList<Device>();

        for (Device device : deviceList) {
            Device deviceNew = new Device(taskPlanningId, device.getDeviceId(), device.getDeviceRunCostPerHour());
            deviceListWithSuperId.add(deviceNew);
            taskPlanningId = taskPlanningId + 1L;
        }
        return deviceListWithSuperId;
    }
}
